package com.qst.crop.controller;

import com.github.pagehelper.PageInfo;
import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.dao.UserDao;
import com.qst.crop.entity.Export;
import com.qst.crop.entity.Order;
import com.qst.crop.entity.UpdatePassword;
import com.qst.crop.entity.User;
import com.qst.crop.security.entity.JwtUser;
import com.qst.crop.service.ExportService;
import com.qst.crop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
@Api("用户管理相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;

    /**
     * @Description : 获取用户信息
     *  * @param pageNum
     * @Return : com.qst.crop.common.Result<com.github.pagehelper.PageInfo>
     */
    @GetMapping("search/{pageNum}")
    @ApiOperation("获取用户信息")
    public Result<PageInfo> getUserAll(@PathVariable("pageNum")Integer pageNum){
        log.info("获取用户信息");
        PageInfo<User> pageInfo = userService.findAll(pageNum);

        return new Result<PageInfo>(true, StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * @Description : 通过用户名获取用户信息
     *  * @param username
     * @Return : com.qst.crop.common.Result<com.qst.crop.entity.User>
     */
    @ApiOperation("通过用户名获取用户信息")
    @GetMapping("{username}")
    public Result<User> getUserByName(@PathVariable String username){
        log.info("通过用户名获取用户信息");
        User user = userService.selectByUserName(username);
        return new Result<User>(true, StatusCode.OK,"查询成功",user);
    }

    /**
     * @Description : 修改用户信息
     *  * @param user
     * @param username
     * @Return : com.qst.crop.common.Result
     */
    @PutMapping("/{username}")
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody User user,@PathVariable String username){
        log.info("修改用户信息");
        user.setUserName(username);
        userService.update(user);
        return new Result<>(true,StatusCode.OK,"修改成功");
    }
    /**
     * @Description : 删除用户
     *  * @param username
     * @Return : com.qst.crop.common.Result
     */
    @DeleteMapping("/{username}")
    @ApiOperation("删除用户")
    public Result delete(@PathVariable String username){
        log.info("删除用户");
        userService.delete(username);
        return new Result<>(true,StatusCode.OK,"删除成功");
    }


    @PostMapping("/loginUpdateByUsername")
    public Result<Integer> loginUpdateByUsername(@RequestBody User user){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        user.setUserName(username);
        return new Result<>(true,StatusCode.OK,"修改成功",userService.loginUpdateByUsername(user));
    }

    @PostMapping("/loginUpdatePassword")
    public Result<Integer> UpdatePwdByUsername(@RequestBody UpdatePassword updatePassword){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        String password = principal.getPassword();

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String oldPwd = updatePassword.getOldPassword();
        final boolean matches = bCryptPasswordEncoder.matches(oldPwd, password);
        log.info("————————————————————————"+matches);
        if(matches){
            String newPwd = updatePassword.getNewPassword();
            String newPwdjiami = bCryptPasswordEncoder.encode(newPwd);
            log.info("—————————————————————————————————— "+newPwdjiami);
            return new Result<>(true,StatusCode.OK,"修改成功",userService.updatePassword(username,newPwdjiami));

        }
        else{

            return new Result<>(true,StatusCode.OK,"原始密码不正确",null);

        }

//        if(oldPwd.equals(password)){
//            // 原先密码正确
//            principal.setPassword(newPwd);
//            // jiami更新数据库
//            log.info("————————————————————————————————pwd:"+password);
//            return new Result<>(true,StatusCode.OK,"修改成功",userService.updatePassword(username,newPwd));
//        }
//        else{
//            return new Result<>(false, StatusCode.ERROR,"密码错误",null);
//        }

    }

    @GetMapping("/loginSelectByUsername")
    public Result<User> loginSelectByUsername(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        return new Result<>(true,StatusCode.OK,"查询成功",userService.loginSelectByUsername(username));
    }

    @PostMapping("/add")
    public Result<String> add(@Valid @RequestBody User user, BindingResult bingdingResult) throws IOException {
        if(bingdingResult.hasErrors()){
            List<ObjectError> allErrors = bingdingResult.getAllErrors();
            StringBuffer stringBuffer =new StringBuffer();
            for(ObjectError error : allErrors){
                System.out.println(error);
                stringBuffer.append(error.getDefaultMessage()).append("；");
            }
            System.out.println(stringBuffer);
            String errorInfo = stringBuffer.toString();
            return new Result<String>(false, StatusCode.ERROR,"注册失败", errorInfo);
        }
        String userName = user.getUserName();
        User user1 = userDao.selectByPrimaryKey(userName);
        if(user1 != null){
            return new Result<String>(false,StatusCode.ERROR,"注册失败","用户已被注册，请重新登录");
        }
        userService.add(user);
        return new Result(true,StatusCode.OK,"注册成功");
    }

    @GetMapping("/searchexpert")
    public Result<Export> searchExpert(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();

        return new Result<>(true,StatusCode.OK,"success",userService.searchExpert(username));
    }


    @Autowired
    private ExportService exportService;
    @PostMapping("/addUpdexpert")
    public Result<Integer> addUpdExpert(@RequestBody Export export){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        export.setUserName(username);

        return new Result<>(true,StatusCode.OK,"success",exportService.addUpdExpert(export));
    }

    @GetMapping("/initUser")
    public Result<User> initUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        return new Result<>(true,StatusCode.OK,"查询成功",userService.initUser(username));
    }


}
